package edu.ccut.saturn.manager.dict.core;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnDictionaryManager;

public class DeleteDictType extends DefaultComponent {

	private static final String DELETE_DICT_SQL = "DELETE FROM saturn_dict_type  WHERE type = ?";

	private static final String DELETE_DICTPARAM_SQL = "DELETE FROM saturn_dict WHERE type = ?";

	@SuppressWarnings("unchecked")
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		String keys = (String) parameterContext.getParameterValue(0);
		
		String delSucc = "false";	
		List<String> typeList = this.keyList(keys);
		List<String> removeKeys = new ArrayList<String>();

		PreparedStatement statement = null;
		ResultSet rs = null;

		try {
			for (String type : typeList) {
				statement = parameterContext.getConnection().prepareStatement(
						DELETE_DICT_SQL);

				statement.setString(1, type);
				statement.execute();

				statement = parameterContext.getConnection().prepareStatement(
						DELETE_DICTPARAM_SQL);
				statement.setString(1, type);
				statement.execute();

				removeKeys.add(type);
			}
			
            if(removeKeys != null) {
			    delSucc = "true";
            }

		} catch (Exception e) {
			logger.error("found exception when execute Component Node "
					+ this.getComponentFullKey(), e);
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (statement != null) {
				statement.close();
			}
		}

		if ("true".equalsIgnoreCase(delSucc)) {
			for (String key : removeKeys) {
				SaturnDictionaryManager.getInstance().removeBundleDictInfo(key);
			}
		}
		
		parameterContext.setParameter(1, delSucc);
	}
	
	private List<String> keyList(String keys) {	
		
		List<String> keyList = new ArrayList<String>();	
		String[] keyArray = keys.split(",");
		
		for (String key : keyArray) {
			keyList.add(key);
		}
		
		return keyList;
	}
}
